package com.lsh.ofc.worker.task;

import com.alibaba.fastjson.JSON;
import com.lsh.base.common.exception.BusinessException;
import com.lsh.ofc.core.entity.OfcOrderHead;
import com.lsh.ofc.core.entity.OfcSoHead;
import com.lsh.ofc.core.entity.OfcTask;
import com.lsh.ofc.core.enums.FulfillStatus;
import com.lsh.ofc.core.enums.OfcTaskStatus;
import com.lsh.ofc.core.enums.OfcTaskType;
import com.lsh.ofc.core.mail.EmailHandler;
import com.lsh.ofc.core.service.OfcOrderService;
import com.lsh.ofc.core.service.OfcSoCreateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;

/**
 * 创建SO任务
 *
 * @author huangdong
 * @date 16/9/5
 */
@Component
public class OfcSoCreateJob extends AbstractOfcTaskJob {

    @Autowired
    private OfcOrderService ofcOrderService;

    @Autowired
    private OfcSoCreateService ofcSoCreateService;

    @Autowired
    private EmailHandler emailHandler;

    @Override
    protected OfcTaskType getFetchTaskType() {
        return OfcTaskType.SO_CREATE;
    }

    @Override
    protected int processTask(OfcTask task) throws BusinessException {
        Long orderCode = task.getRefId();
        OfcOrderHead filter = new OfcOrderHead();
        filter.setOrderCode(orderCode);
        filter.setFulfillStatus(FulfillStatus.NEW.getValue());
        List<OfcOrderHead> list = ofcOrderService.findList(filter, true);
        if (list == null || list.size() != 1) {
            logger.warn("订单信息不存在，或者订单状态不为\"" + FulfillStatus.NEW.getDesc() + "\"！订单号=" + orderCode);
            return Integer.MAX_VALUE;
        }
        OfcOrderHead ofcOrderHead = null;
        List<OfcSoHead> sos;
        int processFlag = -1;
        try {
            ofcOrderHead = list.get(0);
            sos = this.ofcSoCreateService.prepare(ofcOrderHead);
            if (CollectionUtils.isEmpty(sos)) {
                logger.error("SO信息不存在！订单号=" + orderCode);
                return Integer.MIN_VALUE;
            }
        } catch (BusinessException e) {
            logger.error("订单拆单失败", e);
            this.sendMail(ofcOrderHead.getOrderCode(), e.getCode() + " : " + e.getMessage(), EmailHandler.EmailTopic.SO_CREATE_SPLIT);
            return processFlag;
        } catch (Exception e) {
            logger.error("订单拆单失败", e);
            return processFlag;
        }
        logger.info("创建SO集合：" + JSON.toJSONString(sos));
        try {
            processFlag = ofcSoCreateService.process(ofcOrderHead, sos, null);
        } catch (BusinessException e) {
            logger.error("订单so 推送失败", e);
            this.sendMail(ofcOrderHead.getOrderCode(), e.getCode() + " : " + e.getMessage(), EmailHandler.EmailTopic.SO_CREATE_PRECESS);
            processFlag = -1;
        }

        return processFlag;
    }

    /**
     * 发送邮件
     *
     * @param orderCode
     * @param message
     * @param topic
     */
    private void sendMail(Long orderCode, String message, EmailHandler.EmailTopic topic) {
        StringBuilder builder = new StringBuilder();
        if (StringUtils.isNotBlank(message) && message.length() > 200) {
            message = message.substring(0, 200);
        }
        builder.append("订单号：").append(orderCode).append("\n");
        builder.append("错误信息：").append(message).append("\n");
        this.emailHandler.buildEmail(topic, builder.toString());
    }

    @Override
    protected boolean filterFlag(OfcTask task) {

        return false;
    }

    @Override
    protected List<OfcTask> fetchTasks(OfcTaskType type, Set<OfcTaskStatus> statuses, int shardingCount, List<Integer> shardingItems, int fetchSize) {
        return super.defaultFetchTasks(type, statuses, shardingCount, shardingItems, fetchSize);
    }
}
